# -*- coding:utf-8 -*-
from PIL import Image
import CIELab

def Zoom(image,maxsize,enableZoomup=True):
    '''
    zoomup=Falseの時は、縮小処理のみ
    '''
    
    w,h=image.size
    if enableZoomup or maxsize<w or maxsize<h:
        img2Size=(maxsize,int(maxsize*h/w)) if w>h else (int(maxsize*w/h),maxsize)
        return image.resize(img2Size,Image.BICUBIC)
    else:
        return image

colors=[
    (0,0,0)#black
    ,(128,128,128)#grey
    ,(192,192,192)#silver
    ,(255,255,255)#white
    ,(255,0,0)#red
    ,(255,255,0)#yellow
    ,(0,255,0)#lime
    ,(0,255,255)#aqua
    ,(0,0,255)#blue
    ,(255,0,255)#fuchsia
    ,(128,0,0)#maroon
    ,(128,128,0)#olive
    ,(0,128,0)#green
    ,(0,128,128)#teal
    ,(0,0,128)#navy
    ,(128,0,128)#purple
]
#_color3=(0,127,255)
#colors=[(_c1,_c2,_c3) for _c1 in _color3 for _c2 in _color3 for _c3 in _color3]

def ReduceColor(image,createNew=True):
    '''HTML基本16色に近似'''
    if createNew:
        return ReduceColor(image.copy(),False)

    pix=image.load()
    w,h=image.size
    for y in xrange(h):
        for x in xrange(w):
            c=pix[x,y]
            dcolor=[(color[0]-c[0])**2+(color[1]-c[1])**2+(color[2]-c[2])**2 for color in colors]
            pix[x,y]=colors[dcolor.index(min(dcolor))]
            del dcolor
    return image

def ReduceColorLAB(image,createNew=False):
    '''HTML基本16色に近似(CIELabによる近接計算。遅い。)'''
    if createNew:
        return ReduceColorLAB(image.copy())
    
    labs=[CIELab.FromRGB(rgb[0],rgb[1],rgb[2]) for rgb in colors]
    pix=image.load()
    w,h=image.size
    for x in xrange(w):
        for y in xrange(h):
            c=pix[x,y]
            labc=CIELab.FromRGB(c[0],c[1],c[2]) 
            dlab=[(labc.L-lab.L)*(labc.L-lab.L)+(labc.A-lab.A)*(labc.A-lab.A)+(labc.B-lab.B)*(labc.B-lab.B) for lab in labs]
            pix[x,y]=colors[dlab.index(min(dlab))]
            del dlab
            del labc
    return image